package com.fast.fastenjoy.base.web.tag.tagtemplate.impl;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.fast.fastenjoy.base.utils.StringExUtils;
import com.fast.fastenjoy.base.web.tag.tagtemplate.TagTemplate;

public class ConfigTagTemplate extends TagTemplate{

	private static final Logger LOG = Logger.getLogger(ConfigTagTemplate.class);
	
	private static final String DEFAULT_TEMPLATE_CONFIG_PATH = "classpath*:tag/*.flt";
	
	private String tagTemplateConfigPath = "classpath*:tag/*.flt";
	
	@Override
	public Map<String, String> getAllTagTemplate() {
		
		if(LOG.isInfoEnabled()){
			LOG.info("===========Get TagTemplate by ConfigTagTemplate");
		}
		
		if(StringExUtils.isEmpty(tagTemplateConfigPath)){
			tagTemplateConfigPath = DEFAULT_TEMPLATE_CONFIG_PATH;
		}
		
		Map<String, String> resultMap = new HashMap<String, String>();
		
		PathMatchingResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
		
		try{
			if(resourceLoader instanceof ResourcePatternResolver){
				try{
					Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(tagTemplateConfigPath);
					_builderMap(resources, resultMap);
				}catch(IOException e){
					throw new Exception("Could not resolve tag config definition resource pattern ["+ tagTemplateConfigPath + "]", e);
				}
			}else{
				_builderMap(resourceLoader.getResource(tagTemplateConfigPath), resultMap);
			}
		}catch(Exception e){
			LOG.error("===========ConfigTagTemplate Get Resource error, message:" + e.getMessage());
		}
		
		return resultMap;
	}
	
	private void _builderMap(Resource[] resources, Map<String, String> resultMap) throws Exception{
		for(Resource resource : resources){
			_builderMap(resource, resultMap);
		}
	}
	
	private void _builderMap(Resource resource, Map<String, String> resultMap) throws Exception{
		
		String fileName = resource.getFilename();
		
		File file = resource.getFile();
		
		fileName = fileName.substring(0, fileName.length() - 4);
		
		String tagTemplate = FileUtils.readFileToString(file);
		
		resultMap.put(fileName, tagTemplate);
	}

	public String getTagTemplateConfigPath() {
		return tagTemplateConfigPath;
	}

	public void setTagTemplateConfigPath(String tagTemplateConfigPath) {
		this.tagTemplateConfigPath = tagTemplateConfigPath;
	}

}
